package com.baibei.ebec.quotation.converter;

import android.text.TextUtils;
import android.util.SparseArray;

import com.baibei.ebec.quotation.QuotationInfoCache;
import com.baibei.model.QuotationInfo;
import com.baibei.quotation.IActionDispatch;
import com.baibei.quotation.QuotationFilter;
import com.blankj.utilcode.utils.LogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 行情解析
 * Created by ChenRui on 2017/8/10 0010 10:18.
 */
public class QuotationInfoConverter implements IActionDispatch<SparseArray<QuotationInfo>> {


    public QuotationInfoConverter() {
    }

    @Override
    public boolean handleAction(String action) {
        return TextUtils.equals(action, QuotationFilter.ACTION_QUOTATION_PRODUCT);
    }

    @Override
    public SparseArray<QuotationInfo> convert(String content) throws Exception {
        JSONArray arr = new JSONArray(content);
        int length = arr.length();
        for (int i = 0; i < length; i++) {
            JSONObject obj = arr.getJSONObject(i);
            int productId = obj.getInt("productId");
            QuotationInfo m = QuotationInfoCache.get(productId); // 缓存对象
            m.setMarketPrice(obj.getDouble("productPrice")); // 市价
//            LogUtils.e("tags",obj.getDouble("productPrice"));
            //订货，最高价最低价
            m.setLast(obj.getDouble("productPrice"));
            m.setHigh(obj.getDouble("high"));
            m.setLow(obj.getDouble("low"));
        }

        return QuotationInfoCache.get();
    }


    @Override
    public boolean dispatch(QuotationFilter quotationFilter, Object object) {
        return true; // 默认只要注册了都推送
    }

    @Override
    public boolean canCache() {
        return true;
    }
}
